Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    currentDate: Date.now(),
    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: ''
  },
  openHouseLayer() {
    this.setData({
      houseLayerVisible: true
    })
  },
  closeHouseLayer() {
    this.setData({
      houseLayerVisible: false
    })
  },
  openDateLayer() {
    this.setData({
      dateLayerVisible: true
    })
  },
  closeDateLayer() {
    this.setData({
      dateLayerVisible: false
    })
  },
  goPassport() {
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index',
    })
  },
  selectHouse(ev) {
    // 冒号是重命名
    // 等号是默认值，右边有会使用右边的，没有就使用默认值
    const {
      id: houseId,
      name: houseName,
      address = '河南'
    } = ev.detail
    this.setData({
      houseId,
      houseName
    })
  },
  selectDate(ev) {
    this.setData({
      dateLayerVisible: false,
      visitDate: wx.utils.formatDate(ev.detail)
    })
  },
  onLoad() {
    this.getHouseList()
  },
  async getHouseList() {
    const {
      code,
      data: houseList
    } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败')
    this.setData({
      houseList
    })
  },
  verifyHouseInfo() {
    const valid = this.data.houseId !== ''
    if (!valid) wx.utils.toast('房屋信息为空')
    return valid
  },
  verifyName() {
    // 正则表达式
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    // 验证业主姓名
    const valid = reg.test(this.data.name.trim())
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写真实中文姓名!')
    // 返回验证结果
    return valid
  },
  verifyMobile() {
    // 验证手机号
    const reg = /^1[3-9]\d{9}$/
    const valid = reg.test(this.data.mobile)
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写正确的手机号码!')
    // 返回验证结果
    return valid
  },
  verifyTime() {
    const valid = this.data.visitDate !== ''
    if (!valid) wx.utils.toast('请填写访客日期!')
    return valid
  },
  async submitForm() {
    if (!this.verifyHouseInfo()) return
    if (!this.verifyName()) return
    if (!this.verifyMobile()) return
    if (!this.verifyTime()) return
    const {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    } = this.data
    // 校验通过
    const {
      code,
      data
    } = await wx.http.post('/visitor', {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    })
    if (code !== 10000) return wx.utils.toast('添加访客信息失败')
    // 跳转到二维码页面，同时传递过去后端返回的访客 ID
    wx.navigateTo({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  }
})